// 修复页面JS文件中的语法错误
const fs = require('fs')
const path = require('path')

// 页面路径列表
const pagePaths = [
  'pages/service/civil-affairs/apply',
  'pages/common/search-results',
  'pages/common/index',
  'pages/admin/cases',
  'pages/service/index',
  'pages/service/comprehensive-governance/dispute-mediation',
  'pages/user/mine',
  'pages/user/favorites',
  'pages/user/progress',
  'pages/auth/forgot-password',
  'pages/auth/login',
  'pages/auth/bind-email',
  'pages/auth/register',
  'pages/user/mine/profile',
  'pages/activity/detail',
  'pages/admin/activities',
  'pages/user/activities',
  'pages/admin/notices',
  'pages/user/progress/detail',
  'pages/admin/cases/detail',
  'pages/admin/users',
  'pages/admin/index',
  'pages/admin/chart-analysis',
  'pages/admin/stats',
  'pages/village/notice-detail',
  'pages/service/civil-affairs/pension-subsidy',
  'pages/service/public-services/streetlight-repair',
  'pages/village/complaints',
  'pages/admin/feedback',
  'pages/service/certificate-services/resident-proof',
  'pages/service/comprehensive-governance/security-incident-report',
  'pages/service/agriculture-rural/machinery-subsidy',
  'pages/service/urban-rural-construction/homestead-apply',
  'pages/service/civil-affairs/relief',
  'pages/village/open',
  'pages/common/about',
  'pages/village/cases'
]

// 修复JS文件中的语法错误
function fixJsSyntax(pagePath) {
  const jsPath = path.join(__dirname, '..', pagePath, 'index.js')
  
  if (!fs.existsSync(jsPath)) {
    console.log(`跳过不存在的JS文件: ${jsPath}`)
    return
  }

  try {
    let jsContent = fs.readFileSync(jsPath, 'utf8')
    let hasChanges = false
    
    // 修复重复的逗号
    if (jsContent.includes(',,')) {
      jsContent = jsContent.replace(/,,+/g, ',')
      hasChanges = true
    }
    
    // 修复data对象外的全局加载状态定义
    if (jsContent.includes('globalLoading: false,') && !jsContent.includes('data: {')) {
      // 将全局加载状态移到data对象内
      const dataStart = jsContent.indexOf('data: {')
      if (dataStart !== -1) {
        const dataEnd = jsContent.indexOf('}', dataStart) + 1
        const beforeData = jsContent.slice(0, dataEnd)
        const afterData = jsContent.slice(dataEnd)
        
        // 移除data对象外的全局加载状态定义
        const cleanedAfterData = afterData.replace(/^\s*\/\/\s*全局加载状态\s*\n\s*globalLoading:\s*false,\s*\n\s*globalLoadingText:\s*'[^']*',\s*\n/g, '')
        
        jsContent = beforeData + cleanedAfterData
        hasChanges = true
      }
    }
    
    // 确保onReady方法中有隐藏加载效果的代码
    if (jsContent.includes('onReady()') && !jsContent.includes('hideGlobalLoading')) {
      const onReadyStart = jsContent.indexOf('onReady()')
      const onReadyEnd = jsContent.indexOf('}', onReadyStart) + 1
      const onReadyContent = jsContent.slice(onReadyStart, onReadyEnd)
      
      if (!onReadyContent.includes('hideGlobalLoading')) {
        const newOnReadyContent = onReadyContent.replace(
          'onReady() {',
          `onReady() {
    // 页面准备完成，隐藏加载效果
    setTimeout(() => {
      this.hideGlobalLoading()
    }, 500)`
        )
        
        jsContent = jsContent.replace(onReadyContent, newOnReadyContent)
        hasChanges = true
      }
    }
    
    if (hasChanges) {
      fs.writeFileSync(jsPath, jsContent)
      console.log(`✓ 修复语法错误: ${pagePath}`)
    } else {
      console.log(`✓ 无需修复: ${pagePath}`)
    }
  } catch (error) {
    console.error(`✗ 修复失败: ${pagePath}`, error.message)
  }
}

// 主函数
function main() {
  console.log('开始修复页面JS文件中的语法错误...\n')
  
  let successCount = 0
  let totalCount = pagePaths.length
  
  pagePaths.forEach((pagePath, index) => {
    console.log(`[${index + 1}/${totalCount}] 处理页面: ${pagePath}`)
    
    try {
      fixJsSyntax(pagePath)
      successCount++
    } catch (error) {
      console.error(`✗ 失败: ${pagePath}`, error.message)
    }
  })
  
  console.log(`\n修复完成! 成功: ${successCount}/${totalCount}`)
}

// 运行脚本
if (require.main === module) {
  main()
}

module.exports = {
  fixJsSyntax,
  pagePaths
}
